package business

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/business"
	businessReq "github.com/flipped-aurora/gin-vue-admin/server/model/business/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
)

type PeopleService struct {
}

// CreatePeople 创建答题人员信息记录
// Author [piexlmax](https://github.com/piexlmax)
func (peopleService *PeopleService) CreatePeople(people *business.People) (err error) {
	err = global.GVA_DB.Create(people).Error
	return err
}

// DeletePeople 删除答题人员信息记录
// Author [piexlmax](https://github.com/piexlmax)
func (peopleService *PeopleService) DeletePeople(people business.People) (err error) {
	err = global.GVA_DB.Delete(&people).Error
	return err
}

// DeletePeopleByIds 批量删除答题人员信息记录
// Author [piexlmax](https://github.com/piexlmax)
func (peopleService *PeopleService) DeletePeopleByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]business.People{}, "id in (?)", ids.Ids).Error
	return err
}

// UpdatePeople 更新答题人员信息记录
// Author [piexlmax](https://github.com/piexlmax)
func (peopleService *PeopleService) UpdatePeople(id uint, peopleMap map[string]interface{}) (err error) {
	err = global.GVA_DB.Model(&business.People{}).Where("id =?", id).Updates(&peopleMap).Error
	return err
}

// GetPeople 根据id获取答题人员信息记录
// Author [piexlmax](https://github.com/piexlmax)
func (peopleService *PeopleService) GetPeople(id uint) (people business.People, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&people).Error
	return
}

// GetPeopleInfoList 分页获取答题人员信息记录
// Author [piexlmax](https://github.com/piexlmax)
func (peopleService *PeopleService) GetPeopleInfoList(info businessReq.PeopleSearch) (list []business.People, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&business.People{})
	var peoples []business.People
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Phone != "" {
		db = db.Where("phone = ?", info.Phone)
	}
	if info.QuestionnaireUuid != "" {
		db = db.Where("questionnaire_uuid = ?", info.QuestionnaireUuid)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&peoples).Error
	return peoples, total, err
}
